package com.jokins.admin.vue.hefeng.action;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jokins.admin.vue.hefeng.actioncontext.GetWeatherListDoc;
import com.jokins.admin.vue.hefeng.mapper.CityMapper;
import com.jokins.admin.vue.hefeng.utils.FetchCityDataFromExternal;
import com.jokins.admin.vue.hefeng.vo.CityVo;
import com.jokins.common.actions.action.ActionContext;
import com.jokins.common.actions.action.BaseAction;
import com.jokins.common.actions.exception.BusinessException;
import com.jokins.common.config.CustomCacheManager;
import com.jokins.common.entry.hefeng.City;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class GetWeatherListDocAction extends BaseAction<GetWeatherListDoc> {

    @Autowired
    CityMapper cityMapper;

    @Autowired
    private CustomCacheManager cacheManager;

    @Override
    @Transient
    protected void process(GetWeatherListDoc actionContext) throws BusinessException {
        String cityName = actionContext.getCityName();
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("LOWER(name)", cityName.toLowerCase())
                .or()
                .like("LOWER(abbreviation)", cityName.toLowerCase());
        List<City> cityList;
        List<CityVo> cityVoList = new ArrayList<>();
        cityList = cityMapper.selectList(queryWrapper);
        if (cityList.isEmpty()) {
            cityList = FetchCityDataFromExternal.API(cityName);
            log.info("从外部API获取城市列表:{}", cityList);
            cityMapper.saveList(cityList);
            // 在数据写入后刷新缓存
            cacheManager.cacheManager();
            cityList = cityMapper.selectList(queryWrapper);
        } else {
            // 将 cityList 转换为 cityVoList
            cityVoList = cityList.stream()
                    .map(CityVo::new)
                    .collect(Collectors.toList());
        }
        actionContext.setResult(ActionContext.RESULT_DOC_KEY, cityVoList);
        log.info("查询到的城市列表为: {}", cityVoList);
    }
}
